package org.millioncall.yueyoga.admin.service.impl;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.millioncall.yueyoga.admin.dao.RoleDAO;
import org.millioncall.yueyoga.admin.model.Authority;
import org.millioncall.yueyoga.admin.model.Group;
import org.millioncall.yueyoga.admin.model.Role;
import org.millioncall.yueyoga.admin.service.SecurityService;
import org.springframework.stereotype.Service;

@Service
public class SecurityServiceImpl implements SecurityService {
	public RoleDAO getRoleDAO() {
		return roleDAO;
	}

	public void setRoleDAO(RoleDAO roleDAO) {
		this.roleDAO = roleDAO;
	}

	private RoleDAO roleDAO;

	@Override
	public List<Group> getAllGroups(List<Group> groups, boolean needEnabled) {
		List<Group> rtn = new ArrayList<Group>();
		for (Group group : groups) {
			if (group.isGroupEnabled()) {
				rtn.add(group);
			}
		}
		return rtn;
	}

	// 获得用户组的所有角色
	@Override
	public Set<Role> getRolesByGroups(List<Group> groups, boolean needEnabled) {
		if (groups == null || groups.size() == 0) {
			return null;
		}
		Set<Role> roles = new HashSet<Role>();// 保证其中的角色不重复
		for (Group group : groups) {
			List<Role> dbroles = group.getRoles();
			for (Role role : dbroles) {
				if (needEnabled) {
					if (role.isRoleEnabled()) {
						roles.add(role);
					}
				} else {
					roles.add(role);
				}
				List<String> inheritRoles = role.getInherit();
				if (inheritRoles != null && inheritRoles.size() > 0) {// 如果本角色还有继承的角色
					List<Role> inRoleList = this.roleDAO.findAllByNames(
							inheritRoles, needEnabled);// 取得所有角色
					for (Role inheritRole : inRoleList) {
						roles.add(inheritRole);
					}
				}
			}
		}
		return roles;
	}

	// 获得用户组的所有权限
	@Override
	public Set<Authority> getAuthoritiesByRoles(Set<Role> roles,
			boolean needEnabled) {
		if (roles.size() == 0) {
			return null;
		}
		Set<Authority> authorities = new HashSet<Authority>();// 保证其中的权限不重复
		for (Role role : roles) {
			List<Authority> tempAuthorities = role.getAuthorities();
			for (Authority authority : tempAuthorities) {
				if (needEnabled) {
					if (authority.isAuthorityEnabled()) {
						authorities.add(authority);
					}
				} else {
					authorities.add(authority);
				}
			}
		}
		return authorities;
	}
}